import { ref } from 'vue'
import { getCompanyListApi, createCompanyApi, updateCompanyApi, deleteCompanyApi } from '@/api/company'

export function useCompanyForm(options = {}) {
    const {
        defaultValues = {},
        onSuccess,
        onError,
        onDelete,
    } = options

    const loading = ref(false)
    const companyForm = ref(null)

    const form = ref({
        id: null,
        name: '',
        status: 1,
        phone: '',
        company_code: '',
        sector_id: '',       // 存储行业ID的字符串，以逗号分隔
        sector_id_array: [], // 用于级联选择器显示的数组
        product_name: '',
        comment: '',
        location: '',
        latitude: '',
        longitude: '',
        zoom: 17,
        location_id: '',     // 存储地区ID的字符串，以逗号分隔
        location_id_array: [], // 用于级联选择器显示的数组
        expire: 0,        // 到期时间，使用13位时间戳
        neverExpire: true,   // 是否永不到期的标记
        ...defaultValues
    })

    const rules = {
        name: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
        status: [{ required: true, message: '请选择公司状态', trigger: 'change' }],
        company_code: [{ required: true, message: '请输入公司代码', trigger: 'blur' }],
        phone: [
            { required: true, message: '请输入联系电话', trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        sector_id: [{ required: true, message: '请选择行业', trigger: 'change' }],
        location_id: [{ required: true, message: '请选择省市区', trigger: 'change' }],
        location: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        latitude: [{ required: true, message: '纬度不能为空', trigger: 'blur' }],
        longitude: [{ required: true, message: '经度不能为空', trigger: 'blur' }]
    }

    const fetchCompanyDetails = async (id) => {
        if (!id) return
        loading.value = true
        try {
            const res = await getCompanyListApi({ id })
            if (res.code === 200) {
                const companyData = res.data.companies[0]

                // 处理 sector_id（字符串）转为 sector_id_array（数组）
                if (companyData.sector_id && typeof companyData.sector_id === 'string') {
                    companyData.sector_id_array = companyData.sector_id.split(',')
                } else {
                    companyData.sector_id_array = []
                }

                // 处理 location_id（字符串）转为 location_id_array（数组）
                if (companyData.location_id && typeof companyData.location_id === 'string') {
                    companyData.location_id_array = companyData.location_id.split(',')
                } else {
                    companyData.location_id_array = []
                }

                // 处理到期时间
                if (companyData.expire) {
                    // 如果后端返回的不是数字格式（可能是字符串），确保转换为数字
                    companyData.expire = Number(companyData.expire)
                    companyData.neverExpire = false
                } else {
                    companyData.expire = 1
                    companyData.neverExpire = true
                }

                Object.assign(form.value, companyData)
            } else {
                throw new Error(res.message || '加载公司详情失败')
            }
        } catch (error) {
            onError?.(error)
            throw error
        } finally {
            loading.value = false
        }
    }

    const submitForm = async () => {
        if (!companyForm.value) return

        try {
            const valid = await companyForm.value.validate()
            if (!valid) {
                throw new Error('请完善公司信息')
            }
            loading.value = true
            const api = form.value.id ? updateCompanyApi : createCompanyApi

            // 创建提交数据的副本
            const submitData = { ...form.value }

            // 确保 sector_id 是字符串格式
            if (Array.isArray(submitData.sector_id)) {
                submitData.sector_id = submitData.sector_id.join(',')
            }

            // 确保 location_id 是字符串格式
            if (Array.isArray(submitData.location_id)) {
                submitData.location_id = submitData.location_id.join(',')
            }

            // 处理到期时间 - 1`表示永不过期
            if (submitData.neverExpire) {
                submitData.expire = 1
            }

            // 移除不需要提交到后端的数组字段
            delete submitData.sector_id_array
            delete submitData.location_id_array
            delete submitData.neverExpire

            console.log("提交数据:", submitData);
            const res = await api(submitData)
            if (res.code === 200) {
                onSuccess?.()
            } else {
                throw new Error(res.message || '操作失败')
            }
        } catch (error) {
            onError?.(error)
            throw error
        } finally {
            loading.value = false
        }
    }

    const deleteCompany = async () => {
        if (!form.value.id) return

        try {
            loading.value = true
            const res = await deleteCompanyApi({ id: form.value.id })

            if (res.code === 200) {
                onDelete?.()
            } else {
                throw new Error(res.message || '删除失败')
            }
        } catch (error) {
            onError?.(error)
            throw error
        } finally {
            loading.value = false
        }
    }

    const resetForm = () => {
        if (companyForm.value) {
            companyForm.value.resetFields()
        }
        // 重置表单时初始化默认值
        form.value = {
            id: null,
            name: '',
            status: 1,
            phone: '',
            company_code: '',
            sector_id: '',
            sector_id_array: [],
            product_name: '',
            comment: '',
            location: '',
            latitude: '',
            longitude: '',
            zoom: 17,
            location_id: '',
            location_id_array: [],
            expire: 0,
            neverExpire: true,
            ...defaultValues
        }
    }

    return {
        form,
        rules,
        loading,
        companyForm,
        fetchCompanyDetails,
        submitForm,
        deleteCompany,
        resetForm
    }
}